package cmd

import (
	"os"
	"os/signal"
	"syscall"

	"gitee.com/fanshuaiself/wss-gateway/plugins/discovery"
	"gitee.com/fanshuaiself/wss-gateway/plugins/register"
	"gitee.com/fanshuaiself/wss-gateway/plugins/server"
	log "github.com/sirupsen/logrus"
)

type Kernel interface {
	Start(globalCh chan struct{}) error
	Stop()
}

type KernelHub struct {
	Kernels []Kernel
	globalCh chan struct{}
}

func NewKernelHub() *KernelHub {
	h := KernelHub{
		Kernels: make([]Kernel, 0),
		globalCh: make(chan struct{}, 1),
	}
	h.Kernels = []Kernel{
		register.NewRegisterPlugin(),
		discovery.NewDiscovery(),
		server.NewServerPlugin(h.globalCh),
	}
	return &h
}

func (h *KernelHub) Start() error {
	var err error
	for _, kernel := range h.Kernels {
		err := kernel.Start(h.globalCh)
		if err != nil {
			break
		}
	}
	if err != nil {
		h.Stop()
		return err
	}

	ch := make(chan os.Signal, 1)
	signal.Notify(ch, syscall.SIGTERM, syscall.SIGQUIT, syscall.SIGUSR1)

	select {
	case <- ch:
		log.Print("监听到退出事件")
		break
	case <- h.globalCh:
		break
	}

	h.Stop()
	return nil
}

func (h *KernelHub) Stop() {
	for _, kernel := range h.Kernels {
		kernel.Stop()
	}
}